package com.fuluwa.infra.lucene;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.UpdateParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fuluwa.infra.consts.LucenceConsts;
import com.fuluwa.infra.web.Result;
@Component
public class LuceneServiceImpl implements LuceneService {
	protected final static Logger logger = LoggerFactory.getLogger(LuceneServiceImpl.class);
	private static HttpSolrServer solrServer;

	public LuceneServiceImpl() {
		init(LucenceConsts.SOLR_SERVER_URL);
	}

	public SolrServer getSolrServer() {
		return solrServer;
	}

	private void init(String url) {
		try {
			solrServer = new HttpSolrServer(url);
			solrServer.setSoTimeout(8000); // socket read timeout
			solrServer.setConnectionTimeout(8000);
			solrServer.setDefaultMaxConnectionsPerHost(100);
			solrServer.setMaxTotalConnections(100);
			solrServer.setFollowRedirects(false); // defaults to false
			solrServer.setAllowCompression(true);
			solrServer.setMaxRetries(1); // defaults to 0. > 1 not recommended.
			solrServer.setParser(new XMLResponseParser());

		} catch (Exception e) {
			throw new LuceneException("init solr server error", e);
		}

	}

	@Override
	public Result indexAddOrUpdadate(String uniquenID,Map<String,Object> fields) {
		UpdateRequest req = new UpdateRequest("/update");

		req.setParam(UpdateParams.COMMIT, "true");
		try {
			SolrInputDocument document=new SolrInputDocument();
			document.addField("id", uniquenID);
			for (Entry<String, Object> m : fields.entrySet()) {
				document.addField(m.getKey(), LuceneHelper.dynamicUpdate(m.getValue()));
			}
			req.add(document);
			UpdateResponse response = req.process(solrServer);
			return (response.getStatus() == 0) ? Result.getSuccessResult() : Result.getFailResult("");
		} catch (Exception e) {
			throw new LuceneException("update index error", e);
		}
	}

	@Override
	public Result indexDelete(String uniquenID) {
		UpdateRequest req = new UpdateRequest("/update");

		req.setParam(UpdateParams.COMMIT, "true");
		try {
			req.deleteById(uniquenID);
			UpdateResponse response = req.process(solrServer);
			return (response.getStatus() == 0) ? Result.getSuccessResult() : Result.getFailResult("");
		} catch (Exception e) {
			throw new LuceneException("delete index error", e);
		}
	}

}
